(function () {
	
	$("#avatar").error(function() { 
		$(this).attr("src", "../img/upload.png"); 
		$(this).error=null;
	}); 
	var image;
	$("body").on("change", "#file", function (){
		var $file = $(this);
		var fileObj = $file[0];
		var windowURL = window.URL || window.webkitURL;
		var dataURL;
		var $img = $("#avatar");
		
		if (fileObj && fileObj.files && fileObj.files[0]) {
		    dataURL = windowURL.createObjectURL(fileObj.files[0]);
		} else {
		    dataURL = $file.val();
		    var imgObj = document.getElementById("preview");
		    // 两个坑:
		    // 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
		    // 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
		    imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
		    imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
		}
		$img.attr('src', dataURL);
		//限制上传图片像素大小
//		image = new Image();
//		image.src = dataURL;
//		image.onload = function() { 
//			var height = image.height;
//			var width = image.width;
//			if(width > 30 && height > 30){
//				message('请上传30*30像素');
//				$file.val(""); 
//				return false;
//			}
//			$img.attr('src', dataURL);
//		}
	});
	
	jQuery('#fileclick').on('click', function () {
		if(jQuery('.saveBtn').attr('disabled') && jQuery('.saveBtn').attr('disabled') == 'disabled'){
			return false;
		}else{
			return  $("#file").click();
		}
	});
	
	//添加菜单，弹出弹窗
    jQuery('.addBtn').on('click', function () {
    		jQuery('#id').val('');
    		jQuery('#goodsName').val('');
    		
    		removeDisabled();
    		
        jQuery('#goodsName').val('');
        jQuery('#goodsPrice').val('');
        jQuery('#goodsMemo').val('');
    		
    		var file = $("#file") 
    		file.after(file.clone().val("")); 
    		file.remove(); 
    		
    		jQuery("#iconAddress").val('');
    		jQuery("#avatar").attr('src','../img/upload.png');
    		
    		setButtonShow(true,false,true); 
    });
   
    
    //table数据显示
    var serverData = {};
    var	serverTable;
    
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/goods/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [{
                		data: null,
                		defaultContent: ""
            		},
    	            {
	            		data: 'iconAddress',
	            		render: function (data, type, full, meta) {
                        if (data && data != ''){
                        		var iconAddress = window.rootPath+'/'+ data;
                        		var operate = '<img src="'+iconAddress+'" width="30px" height="30px"/>';
                            return operate;
                        }else{
                            return '';
                        }
                    }
	            },
                {
            			data: 'goodsName'
                },
                {
                		data: 'goodsPrice'
                },
                {
                		data: 'goodsMemo'
                },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate ='<button type="button" class="btn btn-sm btn-info editBtn" title="查看详情"><i class="fa fa-search"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>';

                        return operate;

                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-remove')!=-1 || target.className.indexOf('delBtn')!=-1){

                        deleteInfo(data);
                    }

                    if(target.className.indexOf('fa-search')!=-1||target.className.indexOf('editBtn')!=-1){

                        editInfo(data);
                    }
                    return;
                } );
            }
        });
        
        var deleteInfo=function(data){
            if(!data) return;
            $.springLemonDialog({
                content:'确认模块：'+data.goodsName+'？',//确认文本
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+"/ui/goods/delete/"+data.id;
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type : "post",
                            dataType:"json",
                            success:function(data){
                                serverTable.draw(false);
                                message("删除信息成功!");
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }

            });

        };
        //编辑信息
        var editInfo=function(data){
            if(!data) return;
            jQuery('#id').val(data.id);
            jQuery('#goodsName').val(data.goodsName);
            jQuery('#goodsPrice').val(data.goodsPrice);
            jQuery('#goodsMemo').val(data.goodsMemo);
            
        		
            
			var file = $("#file") 
	    		file.after(file.clone().val("")); 
	    		file.remove(); 
    		
            var iconAddress = data.iconAddress;
            jQuery('#iconAddress').val(iconAddress);
            if(typeof(iconAddress) != 'undefined' && iconAddress != ''){
            		iconAddress = window.rootPath+'/'+ iconAddress;
            }else{
            		iconAddress = '../img/upload.png';
            }
            $("#avatar").attr('src',iconAddress);
            
            addDisabled();
            setButtonShow(true,true,false);
        };
        
        //查询
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#search').val();
            serverTable.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#search').val('');
            serverData.key ='';
            serverTable.draw();
        });
        
        jQuery('.editInfoBtn').on('click',function(){
    			setButtonShow(true,false,true);
			removeDisabled();
        });
        
        //新增，编辑保存
        jQuery('.saveBtn').on('click',function(){
            if(jQuery("#modalForm") && !jQuery("#modalForm").Validform({tiptype:3, showAllError:true}).check(false)){
                return;
            };
            $("#right").mLoading("showNoIcon");
            var data={
                    id:jQuery('#id').val(),
                    goodsName:jQuery('#goodsName').val(),
                    goodsPrice:jQuery('#goodsPrice').val(),
                    iconAddress : jQuery('#iconAddress').val(),
                    goodsMemo : jQuery('#goodsMemo').val()
                };
            var url=window.rootPath+'/ui/goods/saveGoodsWithFile';
	        	$.ajaxFileUpload({
		    		url : url,
		    		secureuri : false,// 是否需要安全协议
		    		fileElementId : ["file"],// 文件上传的Id属性
		    		dataType : 'json',
		    		data : data,
		    		success : function(result, status) {
		    			message(result.msg);
		    			if(result.code == '1' ){
		    				jQuery('.addBtn').click();
	                    serverTable.draw(false);
                		}
		    			$("#right").mLoading("hide");
		    		}
	        });
        });
        
        jQuery('.addBtn').click();
    });

  
    
    function addDisabled(){
    		jQuery('#goodsName').attr('disabled',true);
        jQuery('#goodsPrice').attr('disabled',true);
        jQuery('#goodsMemo').attr('disabled',true);

    }
    
    function removeDisabled(){
    		jQuery('#goodsName').removeAttr("disabled");
        jQuery('#goodsPrice').removeAttr("disabled");
        jQuery('#goodsMemo').removeAttr("disabled");
    }
    
    function setButtonShow(addBtn,editInfoBtn,saveBtn){
    		if(addBtn){
    			jQuery('.addBtn').removeAttr('disabled'); 
    		}else{
    			jQuery('.addBtn').attr('disabled',true);
    		}
    		if(editInfoBtn){
    			jQuery('.editInfoBtn').removeAttr('disabled'); 
    		}else{
    			jQuery('.editInfoBtn').attr('disabled',true);
    		}
    		if(saveBtn){
    			jQuery('.saveBtn').removeAttr('disabled'); 
    		}else{
    			jQuery('.saveBtn').attr('disabled',true);
    		}
    }
})();